package HOT;

/**
 * Author  zxy
 * Date  2023/8/3 10:42
 */
import java.util.concurrent.Semaphore;

public class PrintSequence {
    private static final int NUM_THREADS = 3;
    private static final int MAX_COUNT = 10;
    private static Semaphore[] semaphores = new Semaphore[NUM_THREADS];

    static {
        for (int i = 0; i < NUM_THREADS; i++) {
            semaphores[i] = new Semaphore(1);
            if (i != 0) {
                try {
                    semaphores[i].acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Thread[] threads = new Thread[NUM_THREADS];

        for (int i = 0; i < NUM_THREADS; i++) {
            final int threadId = i;
            threads[i] = new Thread(() -> print(threadId));
            threads[i].start();
        }
    }

    private static void print(int threadId) {
        int nextThreadId = (threadId + 1) % NUM_THREADS;
        int count = 1;

        while (count <= MAX_COUNT) {
            try {
                semaphores[threadId].acquire();
                System.out.println("Thread " + (threadId + 1) + ": " + (threadId + 1));
                count++;
                semaphores[nextThreadId].release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

